4. The Command Line

Grails' command line system is built on Gant - a simple Groovy wrapper around Apache Ant.

However, Grails takes it a bit further through the use of convention and the grails command. When you type:

grails [command name]
Grails does a search in the following directories for Gant scripts to execute:

Grails will also convert command names that are in lower case form such as run-app into camel case. So typing

grails run-app

Results in a search for the following files:

If multiple matches are found Grails will give you a choice of which one to execute. When the Gant script is executed the "default" target is executed.

To get a list and some help about the available commands type:

grails help

Which outputs usage instructions and the list of commands Grails is aware of:

Usage (optionals marked with *): 
grails [environment]* [target] [arguments]*

Examples: grails dev run-app grails create-app books

Available Targets (type grails help 'target-name' for more info): grails bootstrap grails bug-report grails clean grails compile ...

Refer to the Command Line reference in left menu of the reference guide for more information about individual commands

4.1 Creating Gant Scripts

You can create your own Gant scripts by running the create-script command from the root of your project. For example the following command:

grails create-script compile-sources

Will create a script called scripts/CompileSources.groovy. A Gant script itself is similar to a regular Groovy script except that it supports the concept of "targets" and dependencies between them:

target(default:"The default target is the one that gets executed by Grails") {
	depends(clean, compile)
}
target(clean:"Clean out things") {
	Ant.delete(dir:"output")
}
target(compile:"Compile some sources") {
	Ant.mkdir(dir:"mkdir")
	Ant.javac(srcdir:"src/java", destdir:"output")
}

As demonstrated in the script above, there is an implicit Ant variable that allows access to the Apache Ant API.

You can also "depend" on other targets using the depends method demonstrated in the default target above.

4.2 Re-using Grails scripts

Grails ships with a lot of command line functionality out of the box which is useful to re-use (See the command line reference in the reference guide for info on all the commands). Some of the most useful are the compile, package and bootstrap scripts.

The bootstrap script for example allows you to bootstrap a Spring ApplicationContext instance to get access to the data source and so on:

Ant.property(environment:"env")                             
grailsHome = Ant.antProject.properties."env.GRAILS_HOME"

includeTargets << new File ( "${grailsHome}/scripts/Bootstrap.groovy" )

target ('default': "Load the Grails interactive shell") { depends( configureProxy, packageApp, classpath, loadApp, configureApp )

Connection c try { // do something with connection c = appCtx.getBean('dataSource').getConnection() } finally { c?.close() } }

4.3 Hooking into Events

Grails provides the ability to hook into scripting events. These are events triggered during execution of Grails target and plugin scripts.

The mechanism is deliberately simple and loosely specified. The list of possible events is not fixed in any way, so it is possible to hook into events triggered by plugin scripts, for which there is no equivalent event in the core target scripts.

Defining event handlers

Event handlers are defined in scripts called Events.groovy. Grails searches for these scripts in the following locations:

Whenever an event is fired, all the registered handlers for that event are executed. Note that the registration of handlers is performed automatically by Grails, so you just need to declare them in the relevant Events.groovy file.

Event handlers are blocks defined in Events.groovy, with a name beginning with "event". The following example can be put in your /scripts directory to demonstrate the feature:

eventCreatedArtefact = { type, name ->
   println "Created $type $name"
}

eventStatusUpdate = { msg -> println msg }

eventStatusFinal = { msg -> println msg }

You can see here the three handlers eventCreatedArtefact, eventStatusUpdate, eventStatusFinal. Grails provides some standard events, which are documented in the command line reference guide. For example the compile command fires the following events:

Triggering events

To trigger an event simply include the Init.groovy script and call the event() closure:

Ant.property(environment:"env")
grailsHome = Ant.antProject.properties."env.GRAILS_HOME"
includeTargets << new File ( "${grailsHome}/scripts/Init.groovy" )

event("StatusFinal", ["Super duper plugin action complete!"])

Common Events

Below is a table of some of the common events that can be leveraged:

EventParametersDescription
StatusUpdatemessagePassed a string indicating current script status/progress
StatusErrormessagePassed a string indicating an error message from the current script
StatusFinalmessagePassed a string indicating the final script status message, i.e. when completing a target, even if the target does not exit the scripting environment
CreatedArtefactartefactType,artefactNameCalled when a create-xxxx script has completed and created an artefact
CreatedFilefileNameCalled whenever a project source filed is created, not including files constantly managed by Grails
ExitingreturnCodeCalled when the scripting environment is about to exit cleanly
PluginInstalledpluginNameCalled after a plugin has been installed
CompileStartkindCalled when compilation starts, passing the kind of compile - source or tests
CompileEndkindCalled when compilation is finished, passing the kind of compile - source or tests
DocStartkindCalled when documentation generation is about to start - javadoc or groovydoc
DocEndkindCalled when documentation generation has ended - javadoc or groovydoc
SetClasspathrootLoaderCalled during classpath initialization so plugins can augment the classpath with rootLoader.addURL(...). Note that this augments the classpath after event scripts are loaded so you cannot use this to load a class that your event script needs to import, although you can do this if you load the class by name.
PackagingEndnoneCalled at the end of packaging (which is called prior to the Jetty server being started and after web.xml is generated)
ConfigureJettyJetty Server objectCalled after initial configuration of the Jetty web server.

4.4 Ant and Maven

Ant Integration

When you create a Grails application via the create-app command, Grails automatically creates an Apache Ant build.xml file for you containing the following targets:

Each of these can be run by Ant, for example:

ant war

The build.xml calls into Grails' normal commands and can be used to integrate Grails with a continuous integration server such as CruiseControl or Hudson

Maven Integration

Grails does not provide Maven support out of the box, but there is an external project called Maven Tools for Grails that does provide integration which allows you to create a POM out of an existing Grails project as well as providing hooks into the Maven lifecycle for Grails.

For more information refer to the Maven Tools for Grails site.